from datetime import datetime

from django.db.models import Q
from rest_framework.viewsets import ViewSet

from utils.params_filter import allow_edit, get_page
from .models import SystemPermission, SystemRole, SystemRolePermission
from utils.response import ErrorResponse, SuccessResponse
from .serializers import SystemPermissionSerializer, SystemRoleSerializer, SystemPermissionTreeSerializer, \
	SystemRoleTreeSerializer


class SystemPermissionViewSet(ViewSet):
	# authentication_classes = []

	# 新建/更新权限前置处理
	def create_or_update_before(self, request):
		allow = ['path', 'route_name', 'title', 'url', 'parent_id', 'type', 'sort']
		required = ['path', 'route_name', 'title', 'url', 'parent_id', 'type', 'sort']
		data = allow_edit(allow, request)
		for param in allow:
			if param == 'parent_id' and data.get(param) == 0:
				continue
			elif param == 'sort' and data.get(param) == 0:
				continue
			if not data.get(param) and param in required:
				return ErrorResponse(msg=f'{param}: 是必填项')
		if data.get('type') == 'P':
			data.update({'parent_id': -1})
		return data

	# 添加权限
	def create(self, request):
		data = self.create_or_update_before(request)
		if isinstance(data, ErrorResponse):
			return data
		SystemPermission.objects.create(**data)
		return SuccessResponse(msg='权限添加成功')

	# 权限列表
	def list(self, request):
		data = get_page(request, SystemPermission, SystemPermissionSerializer)
		return SuccessResponse(data=data)

	# 权限详情
	def get_by_id(self, request):
		p_id = request.query_params.get('id')
		if not p_id:
			return ErrorResponse(msg='请求参数错误')
		data = SystemPermission.objects.filter(id=p_id, deleted=False)
		return SuccessResponse(data=SystemPermissionSerializer(data, many=True).data, msg='添加成功')

	# 更新权限
	def update(self, request):
		p_id = request.data.get('id')
		if not p_id:
			return ErrorResponse(msg='请求参数错误')
		data = self.create_or_update_before(request)
		if isinstance(data, ErrorResponse):
			return data
		data.update({'update_time': datetime.now()})
		SystemPermission.objects.filter(id=p_id, deleted=False).update(**data)
		return SuccessResponse(msg='权限修改成功')

	# 删除权限
	def delete(self, request):
		p_id = request.data.get('id')
		if not p_id:
			return ErrorResponse(msg='请求参数错误')
		perm = SystemPermission.objects.filter(id=p_id, deleted=False)
		if not perm:
			return ErrorResponse(msg='权限已删除或不存在')
		perm.update(deleted=True)
		return SuccessResponse(msg='权限已删除')

	# 权限树
	def get_permission_tree(self, request):
		perm = SystemPermission.objects.filter(~Q(type='P')).filter(status=True, deleted=False, parent_id=0)
		data = SystemPermissionSerializer(perm, many=True).data
		return SuccessResponse(data={"list": data})


class SystemRoleViewSet(ViewSet):

	# 新建角色
	def create(self, request):
		name = request.data.get('name')
		ids = request.data.get('ids')
		if not name or not ids:
			return ErrorResponse(msg='请求参数错误')
		data = allow_edit(['name', 'mark'], request)
		role = SystemRole.objects.create(**data)
		for permission_id in ids:
			SystemRolePermission.objects.create(role_id=role.id, permission_id=permission_id)
		return SuccessResponse(msg='角色添加成功')

	# 角色列表
	def list(self, request):
		data = get_page(request, SystemRole, SystemRoleTreeSerializer)
		return SuccessResponse(data=data)

	# 更新角色
	def update(self, request):
		r_id = request.data.get('id')

		if not r_id:
			return ErrorResponse(msg='请求参数错误')

		data = allow_edit(['name', 'mark', 'ids'], request)
		SystemRole.objects.filter(id=r_id).update(name=data.get('name'), mark=data.get('mark'))
		ids = data.get('ids')
		if ids:
			SystemRolePermission.objects.filter(role_id=r_id).delete()
			for permission_id in data.get('ids'):
				SystemRolePermission.objects.create(role_id=r_id, permission_id=permission_id)

		return SuccessResponse(msg='修改成功')

	# 角色详情
	def get_by_id(self, request):
		r_id = request.query_params.get('id')
		if not r_id:
			return ErrorResponse(msg='请求参数错误')
		role = SystemRole.objects.filter(id=r_id, deleted=False)
		if not role:
			return ErrorResponse(msg='角色不存在或已删除')

		return SuccessResponse(data=SystemRoleTreeSerializer(role, many=True).data)

	# 删除角色
	def delete(self, request):
		r_id = request.data.get('id')
		if not r_id:
			return ErrorResponse(msg='请求参数错误')
		role = SystemRole.objects.filter(id=r_id, deleted=False)
		if not role:
			return ErrorResponse(msg='角色不存在或已删除')
		role.update(deleted=True)
		return SuccessResponse(msg='角色已删除')

	# 获取用户角色权限
	def get_user_permission(self, request):
		user_role_id = request.user.role_id

		if not SystemRole.objects.filter(deleted=False, status=True):
			return ErrorResponse(msg='用户权限已删除或已停用')
		data = SystemPermission.objects.filter(parent_id=0)\
			.filter(id__in=SystemRolePermission.objects.filter(role_id=user_role_id).values_list('permission_id', flat=True)).order_by('sort')
		return SuccessResponse(data=SystemPermissionTreeSerializer(data, many=True, context={'role': user_role_id}).data)

	# 不分页角色
	def get_role_list(self, request):
		data = SystemRole.objects.filter(deleted=False, status=True)
		return SuccessResponse(data=SystemRoleSerializer(data, many=True).data)
